package com.to8to.scene.server;

import java.io.ByteArrayInputStream;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.to8to.commons.mongo.DBParam;
import com.to8to.commons.mongo.MongoClientBase;
import com.to8to.commons.mq.ExchangeTypes;
import com.to8to.commons.mq.RabbitMQParam;
import com.to8to.commons.mq.RabbitMQProducer;
import com.to8to.scene.util.LogUtil;

/**
 * Commons.java
 * 作 者：atom.liu
 * 版 本：v2.0
 * 日 期：2015年2月7日
 * 描 述：Commons.properties配置类
 */
public class Commons
{
    public static Logger logger = LoggerFactory.getLogger(Commons.class);

    public static MongoClientBase mongo;

    public static RabbitMQProducer producer;

    public static String queue;

    public static String user_compute_schedule_pattern;

    public static void init(byte[] data)
    {
        PropertiesConfiguration pc = new PropertiesConfiguration();

        try
        {
            if (null == data)
                pc = new PropertiesConfiguration("common.properties");
            else
                pc.load(new ByteArrayInputStream(data));
        }
        catch (ConfigurationException e)
        {
            logger.error("", e);
            return;
        }

        DBParam param;
        try
        {
            param = new DBParam(pc);
            Commons.mongo = new MongoClientBase(param);
            logger.info("配置信息\n mongo:{}/{}/", param);
        }
        catch (Exception e)
        {
            logger.error("初始化Commons.mongo异常！{} \n {}", e, LogUtil.logStackTrace(e));
        }

//        String mqhost = pc.getString("rabbitmq.host");
//       
//        String mquser = pc.getString("rabbitmq.user");
//        String mqpassword = pc.getString("rabbitmq.password");
        RabbitMQParam mqparam = new RabbitMQParam(pc);
        
        mqparam.maxFailTry = 1;
        mqparam.failSleepSec= 1;
        
        Commons.queue = pc.getString("rabbitmq.queue");

//        if (!StringUtils.isEmpty(mqpassword))
//            mqparam.setPassword(mqpassword);
//        if (!StringUtil.isEmpty(mquser))
//            mqparam.setUser(mquser);

        if (!StringUtils.isEmpty(queue))
        {
        	if(producer != null)
        		producer.close();
        	
        	producer = new RabbitMQProducer(mqparam, ExchangeTypes.Simple, Commons.queue);
        }

        user_compute_schedule_pattern = pc.getString("user_compute.schedule_pattern", "0 3 * * *");
        
        logger.info("达人榜计算schedule规则：{}\n", user_compute_schedule_pattern);
    }
}
